package edu.bit.water.service;

import com.alibaba.fastjson.JSON;
import edu.bit.water.dao.EntityEffluentLetDao;
import edu.bit.water.dao.MetaEffluentLetDao;
import edu.bit.water.dto.TableColumnName;
import edu.bit.water.entity.Column;
import edu.bit.water.entity.EntityEffluentLetColumn;
import edu.bit.water.entity.WasteWaterTable1;
import edu.bit.water.view.BasicResult;
import edu.bit.water.view.EntityEffluentLetParams;
import edu.bit.water.view.ResultState;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 废水排放实体表Service层
 *
 * @author HuJishuang
 * @Date 19.07.11
 */
@Service
public class EntityEffluentLetService {

    private final String STANDARD_MESSAGE = "符合国家标准";
    private final String NONSTANDARD_MESSAGE = "不符合国家标准";
    private final String EVA_RESULT_COLUMN = "eva_result";

    @Autowired
    private MetaEffluentLetDao metaEffluentLetDao;
    @Autowired
    private EntityEffluentLetDao entityEffluentLetDao;

    /**
     * @return 返回元数据表中包含的英文名称和中文名称的记录，也就是实体表中的列
     */
    public String selectTableColumn() {
        List<Map<String, String>> resultList = new ArrayList<>();
        Map<String, String> columnMap = new HashMap<>();
        List<Column> list = metaEffluentLetDao.selectEnAndCs();
        for (Column column : list) {
            columnMap = new HashMap<>();
            columnMap.put("title", column.getCsName());
            columnMap.put("field", column.getEnName());
            resultList.add(columnMap);
        }
        Map<String, String> evaResultMap = new HashMap<>();
        evaResultMap.put("title", "评估结果");
        evaResultMap.put("field", EVA_RESULT_COLUMN);
        resultList.add(evaResultMap);
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, resultList, null));
    }

    /**
     * @param entityEffluentLetParams 该参数包含一系列键值对
     * @return 结果
     */
    public String insert(EntityEffluentLetParams entityEffluentLetParams) {
        //entityEffluentLetParams.showContent();
        String result = STANDARD_MESSAGE;
        List<String> sqlCloumnList = new ArrayList<>();
        List<Object> sqlValueList = new ArrayList<>();
        Map<String, Double> paramMap = entityEffluentLetParams.getParams();
        Set<String> paramKeySet = paramMap.keySet();
        List<EntityEffluentLetColumn> list = metaEffluentLetDao.selectEnAndValue();
        Iterator<EntityEffluentLetColumn> iterator = list.iterator();
        while (iterator.hasNext()) {
            EntityEffluentLetColumn entityEffluentLetColumn = iterator.next();
            String enName = entityEffluentLetColumn.getEnName();
            if (!paramKeySet.contains(enName)) {
                return JSON.toJSONString(new BasicResult(ResultState.FAILURE.code, null, "参数传递错误"));
            } else {
                sqlCloumnList.add(enName);
                sqlValueList.add( "'" + paramMap.get(enName) + "'");
                if (!compareInputWithStandard(paramMap.get(enName), entityEffluentLetColumn.getLowerLimitValue(), entityEffluentLetColumn.getUpperLimitValue())) {
                    String msg = TableColumnName.getNameByColumn(enName);
                    //System.out.println(msg);
                    if (result.equals(STANDARD_MESSAGE)) {
                        result = msg + "," + NONSTANDARD_MESSAGE;
                    }
                    else {
                        result = msg + "," + result;
                    }
                }
            }
        }
        Integer id = entityEffluentLetDao.getMaxId();
        if (id == null) {
            id = -1;
        }
        sqlCloumnList.add(EVA_RESULT_COLUMN);
        sqlValueList.add("'" + result + "'");
        sqlCloumnList.add("id");
        sqlValueList.add(id + 1);
        sqlCloumnList.add("waste_water_id");
        sqlValueList.add(entityEffluentLetParams.getParams().get("waste_water_id"));
        Map<String, String> map = new HashMap<>();
        map.put("sqlColumnString", StringUtils.join(sqlCloumnList, ','));
        map.put("sqlValueString", StringUtils.join(sqlValueList, ','));
        int opResult = entityEffluentLetDao.insert(map);
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, result, null));
    }


    /**
     * @return 返回废水排放评估表中的数据记录（包含评估结果）
     */
    public String selectAll(int id) {
        List<Map<String, Double>> list = entityEffluentLetDao.selectAll(id);
        List<Map<String, Object>> listResult = new ArrayList<>();
        Map<String, Object> map = null;
        for (Map<String, Double> mapIndex : list) {
            Iterator<Map.Entry<String, Double>> iterator = mapIndex.entrySet().iterator();
            map = new HashMap<>();
            while (iterator.hasNext()) {
                Map.Entry<String, Double> entry = iterator.next();
                map.put(entry.getKey().toLowerCase(), entry.getValue());
            }
            listResult.add(map);
        }
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, listResult, null));
    }

    /**
     * @param idList 要删除的记录id
     * @return
     */
    public String delete(List<Integer> idList) {
        for (int id : idList) {
            entityEffluentLetDao.delete(id);
        }
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, null, null));
    }

    /**
     * @param entityEffluentLetParams 废水排放评估实体表
     * @return
     */
    public String update(EntityEffluentLetParams entityEffluentLetParams) {
        StringBuilder sqlString = new StringBuilder();
        String result = STANDARD_MESSAGE;
        Map<String, Double> paramMap = entityEffluentLetParams.getParams();
        Set<String> paramKeySet = paramMap.keySet();
        List<EntityEffluentLetColumn> list = metaEffluentLetDao.selectEnAndValue();
        Iterator<EntityEffluentLetColumn> iterator = list.iterator();
        entityEffluentLetParams.getParams();
        while (iterator.hasNext()) {
            EntityEffluentLetColumn entityEffluentLetColumn = iterator.next();
            String enName = entityEffluentLetColumn.getEnName();
            if (!paramKeySet.contains(enName)) {
                return JSON.toJSONString(new BasicResult(ResultState.FAILURE.code, null, "参数传递错误"));
            } else {
                String updateCondition = enName + "=" + "'" + paramMap.get(enName) + "'" + ",";
                sqlString = sqlString.append(updateCondition);
                if (!compareInputWithStandard(paramMap.get(enName), entityEffluentLetColumn.getLowerLimitValue(), entityEffluentLetColumn.getUpperLimitValue())) {
                    String msg = TableColumnName.getNameByColumn(enName);
                    //System.out.println(msg);
                    if (result.equals(STANDARD_MESSAGE)) {
                        result = msg + "," + NONSTANDARD_MESSAGE;
                    }
                    else {
                        result = msg + "," + result;
                    }
                }
            }
        }
        // 将评估结果插入数据库中
        sqlString = sqlString.append(EVA_RESULT_COLUMN + "=" + "'" + result + "'");
        Map<String, Object> sqlMap = new HashMap<>();
        sqlMap.put("sqlString", sqlString);
        sqlMap.put("id", entityEffluentLetParams.getId());
        int opResult = entityEffluentLetDao.update(sqlMap);
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, result, null));
    }

    private boolean compareInputWithStandard(double input, double lowerLimitValue, double upperLimitValue) {
        return input <= upperLimitValue && input > lowerLimitValue;
    }

    public int deleteByWasteWaterId(int id) {
        return entityEffluentLetDao.deleteByWasteWaterId(id);
    }

}
